package com.hmall.controller.back;

import com.hdmall.business.common.annotation.AuthRequired;
import com.hdmall.business.common.common.ServerResponse;

import com.hmall.mapper.*;

import com.hmall.model.*;

import com.hdmall.business.common.util.GetLocation;
import com.hmall.util.TokenUtil;

import com.hmall.vo.DealerVo;
import com.hmall.vo.MallDealerVo;
import com.hmall.vo.MallShippingVo;

import com.hmall.vo.ShopVo2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/manage/dealer")
@Api(value = "后台经销商管理操作API", description = "后台经销商管理类API说明")
public class DealerManageController {
    private final
    MallDealerMapper mallDealerMapper;
    private final
    SysUserMapper sysUserMapper;
    private final ShopCategoryMapper shopCategoryMapper;
    private final ShopAttrMapper shopAttrMapper;
    private final ShopAttrValueMapper shopAttrValueMapper;
    private final
    JedisPool jedisPool;
    private final SysDeptMapper sysDeptMapper;
    private final MallShopMapper mallShopMapper;
    private final ShopGradeMapper shopGradeMapper;

    /*@Autowired
    RedisOperator redisOperator=new RedisOperator();*/
    private TokenUtil tokenUtil = new TokenUtil();

    @Autowired
    public DealerManageController(JedisPool jedisPool, MallDealerMapper mallDealerMapper, SysUserMapper sysUserMapper, ShopCategoryMapper shopCategoryMapper, ShopAttrMapper shopAttrMapper, ShopAttrValueMapper shopAttrValueMapper, SysDeptMapper sysDeptMapper, MallShopMapper mallShopMapper, ShopGradeMapper shopGradeMapper) {
        this.jedisPool = jedisPool;
        this.mallDealerMapper = mallDealerMapper;
        this.sysUserMapper = sysUserMapper;
        this.shopCategoryMapper = shopCategoryMapper;
        this.shopAttrMapper = shopAttrMapper;
        this.shopAttrValueMapper = shopAttrValueMapper;
        this.sysDeptMapper = sysDeptMapper;
        this.mallShopMapper = mallShopMapper;
        this.shopGradeMapper = shopGradeMapper;
    }

    @GetMapping("test")
    @ApiOperation(value = "test")
    public void test() {
        ShopAttr shopAttr = new ShopAttr();
        shopAttr.setOrderNum(1);
        shopAttr.setCreateTime(new Date());
        shopAttr.setCanDelete(0);
        shopAttr.setStatus(1);
        shopAttr.setAttrName("等级");
        List<ShopCategory> list = shopCategoryMapper.selectByShopId(22);
        for (ShopCategory shopCategory : list) {
            shopAttr.setCategoryId(shopCategory.getCategoryId());
            shopAttrMapper.insert(shopAttr);
            Integer attrId2 = shopAttrMapper.selectRepeatData("等级", shopCategory.getCategoryId()).get(0).getAttrId();
            String s1[] = {"无等级"};
            ShopAttrValue shopAttrValue = new ShopAttrValue();
            setAttrValue(shopAttrValue, attrId2, s1);
        }
    }

    //    @AuthRequired
    @PostMapping("addShop")
    @ApiOperation(value = "添加商家")
    public ServerResponse addShop(@RequestBody ShopVo2 shopVo2) {
        Integer deptId = sysDeptMapper.selectIdByName3(shopVo2.getShop_name());
        if (deptId == null) {
            return ServerResponse.createByErrorMessage("卖家不存在");
        }
        MallShop mallShop = new MallShop();
        mallShop.setShopName(shopVo2.getShop_name());
        mallShop.setDeptId(deptId);
        mallShop.setLikeCount(0);
        mallShop.setShopCreateDate(new Date());
        mallShop.setShopLogo(shopVo2.getShop_logo());
        mallShop.setShopSummary(shopVo2.getShop_summary());
        mallShopMapper.insert(mallShop);

        //创建默认属性
        Integer shopId = mallShopMapper.selectByDeptId(deptId);
        String s1[] = {"PX", "PTA", "乙二醇", "POY", "DTY", "FDY", "聚酯切片", "涤纶短纤", "涤纶工业丝", "聚酯瓶片", "涤-锦符合长丝"};
        String s2[] = {"DYU", "FDY", "POY", "HOY", "锦纶短纤", "已内酰胺", "锦纶帘子布", "锦纶切片"};
        String s3[] = {"丙烯腈", "腈纶短纤", "腈纶毛条", "腈纶丝束"};
        String s4[] = {"氨纶", "纯MD"};
        String s5[] = {"FDY", "丙纶短纤"};
        String s6[] = {"粘胶短纤", "有光长丝", "无光长丝"};
        String s7[] = {"仿大化", "中化纤", "小化纤", "原生中空", "再生中空", "再生长丝"};
        createDefaultData(shopId, "聚酯涤纶", s1);
        createDefaultData(shopId, "锦纶", s2);
        createDefaultData(shopId, "腈纶", s3);
        createDefaultData(shopId, "氨纶", s4);
        createDefaultData(shopId, "丙纶", s5);
        createDefaultData(shopId, "粘胶", s6);
        createDefaultData(shopId, "再生化纤", s7);
        return ServerResponse.createBySuccess("创建成功");
    }

    //创建默认数据
    private void createDefaultData(Integer shopId, String categoryName, String[] s) {
        ShopCategory shopCategory = new ShopCategory();
        shopCategory.setCreateTime(new Date());
        shopCategory.setShopId(shopId);
        shopCategory.setStatus(1);
        shopCategory.setCategoryName(categoryName);
        shopCategory.setParentId(0);
        shopCategoryMapper.insert(shopCategory);
        Integer categoryId = shopCategoryMapper.selectRepeatData(categoryName, shopId, 0).get(0).getCategoryId();
        ShopAttr shopAttr = new ShopAttr();
        shopAttr.setOrderNum(1);
        shopAttr.setCreateTime(new Date());
        shopAttr.setCanDelete(0);
        shopAttr.setStatus(1);
        shopAttr.setAttrName("产品分类");
        shopAttr.setCategoryId(categoryId);
        shopAttrMapper.insert(shopAttr);
        Integer attrId = shopAttrMapper.selectRepeatData("产品分类", categoryId).get(0).getAttrId();

        ShopAttrValue shopAttrValue = new ShopAttrValue();
        setAttrValue(shopAttrValue, attrId, s);
        //4.2等级有默认值
        shopAttr.setAttrName("等级");
        shopAttrMapper.insert(shopAttr);
        Integer attrId2 = shopAttrMapper.selectRepeatData("等级", categoryId).get(0).getAttrId();
        String s1[] = {"A", "B", "AA定重", "AA不定重"};
        setAttrValue(shopAttrValue, attrId2, s1);

        //4.2添加等级模板
        ShopGrade shopGrade = new ShopGrade();
        shopGrade.setName("无等级");
        shopGrade.setCanEdit(0);
        shopGrade.setStatus(1);
        shopGrade.setCreateTime(new Date());
        shopGrade.setGrade("无等级");
        shopGradeMapper.insert(shopGrade);
        shopGrade.setName("默认模板");
        shopGrade.setCanEdit(1);
        shopGradeMapper.insert(shopGrade);
    }

    //设置属性值
    private void setAttrValue(ShopAttrValue shopAttrValue, Integer attrId2, String[] s1) {
        for (String value : s1) {
            shopAttrValue.setAttrId(attrId2);
            shopAttrValue.setAddLocation(1);
            shopAttrValue.setValue(value);
            shopAttrValue.setStatus(1);
            shopAttrValue.setCreateTime(new Date());
            shopAttrValueMapper.insert(shopAttrValue);
        }
    }

    //    @AuthRequired
    @PostMapping("updateShop")
    @ApiOperation(value = "更新商家")
    public ServerResponse updateShop(@RequestBody ShopVo2 shopVo2) {
        Integer shop_id = mallShopMapper.selectByDeptId(shopVo2.getDept_id());
        if (shop_id == null) {
            return ServerResponse.createByErrorMessage("商家不存在");
        }
        MallShop mallShop = mallShopMapper.selectByPrimaryKey(shop_id);
        if (shopVo2.getShop_logo() != null && !shopVo2.getShop_logo().equals("")) {
            mallShop.setShopLogo(shopVo2.getShop_logo());
        }
        mallShop.setShopSummary(shopVo2.getShop_summary());
        mallShopMapper.updateByPrimaryKey(mallShop);
        return ServerResponse.createBySuccess("更新成功");
    }

    //    @AuthRequired
    @DeleteMapping("deleteShop")
    @ApiOperation(value = "删除商家")
    public ServerResponse deleteShop(Integer dept_id) {
        Integer shop_id = mallShopMapper.selectByDeptId(dept_id);
        if (shop_id == null) {
            return ServerResponse.createByErrorMessage("商家不存在");
        }
        mallShopMapper.deleteByPrimaryKey(shop_id);
        return ServerResponse.createBySuccess("删除成功");
    }

    //    @AuthRequired
    @GetMapping("getShopDetail")
    @ApiOperation(value = "获取商家信息")
    public ServerResponse getShopDetail(Integer dept_id) {
        Integer shop_id = mallShopMapper.selectByDeptId(dept_id);
        if (shop_id == null) {
            return ServerResponse.createByErrorMessage("商家不存在");
        }
        MallShop mallShop = mallShopMapper.selectByPrimaryKey(shop_id);
        return ServerResponse.createBySuccess(mallShop);
    }

    @AuthRequired
    @GetMapping("findDealerList")
    @ApiOperation(value = "获取经销商列表")
    public ServerResponse<List<MallDealer>> findDealerList() {
        List<MallDealer> dealerList = mallDealerMapper.selectAll();

        return ServerResponse.createBySuccess(dealerList);
    }

    @AuthRequired
    @GetMapping("findDealerList2")
    @ApiOperation(value = "获取经销商列表")
    public ServerResponse<List<MallShippingVo>> findDealerList2() {
        List<MallShippingVo> dealerList = mallDealerMapper.selectAllDealer();

        return ServerResponse.createBySuccess(dealerList);
    }

    @AuthRequired
    @PostMapping("bindingDealer2")
    @ApiOperation(value = "绑定办事处")
    public ServerResponse<String> bindingDealer2(Integer dealer_id, Integer user_id) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(user_id);

        if (sysUser == null) {
            return ServerResponse.createBySuccess("用户不存在");
        }

        sysUser.setDealer_id(dealer_id);
        sysUserMapper.updateByPrimaryKey(sysUser);

        return ServerResponse.createBySuccess("绑定成功");
    }

    @PostMapping("bindingDealer")
    @ApiOperation(value = "绑定办事处")
    public ServerResponse<String> bindingDealer(Integer dealer_id, String token)
            throws Exception {
        Jedis jedis = jedisPool.getResource();
        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();

        if (user == null) {
            return ServerResponse.createBySuccess("用户不存在或token失效");
        }

        SysUser sysUser = sysUserMapper.selectByPrimaryKey(user.getUserId());

        if (sysUser == null) {
            return ServerResponse.createBySuccess("用户不存在或token失效");
        }

        sysUser.setDealer_id(dealer_id);
        sysUserMapper.updateByPrimaryKey(sysUser);

        return ServerResponse.createBySuccess("绑定成功");
    }

    @AuthRequired
    @PostMapping("saveDealer")
    @ApiOperation(value = "保存办事处信息")
    public ServerResponse<String> saveDealer(Integer dealer_id, String dealer_name,
                                             String dealer_phone, String dealer_linkman, String dealer_area,
                                             String dealer_abstract, String short_phone) {
        System.out.println(dealer_id);

        MallDealer mallDealer = mallDealerMapper.selectByPrimaryKey(dealer_id);
        mallDealer.setDealerName(dealer_name);
        mallDealer.setDealerPhone(dealer_phone);
        mallDealer.setDealerAbstract(dealer_abstract);
        mallDealer.setDealerLinkman(dealer_linkman);
        mallDealer.setDealerArea(dealer_area);
        mallDealer.setShort_phone(short_phone);
        mallDealerMapper.updateByPrimaryKey(mallDealer);

        return ServerResponse.createBySuccess("保存成功");
    }

    @AuthRequired
    @GetMapping("GetDealer")
    @ApiOperation(value = "获取经销商信息")
    public ServerResponse<DealerVo> GetDealer(Integer dept_id) {
        DealerVo mallDealer = mallDealerMapper.selectByDeptId(dept_id);

        return ServerResponse.createBySuccess(mallDealer);
    }

    @AuthRequired
    @GetMapping("GetRecommend")
    @ApiOperation(value = "获取推荐经销商")
    public ServerResponse GetRecommend(String x, String y) {
        String[] arr = GetLocation.getAdd(x, y);
        System.out.println("省:" + arr[0] + "\n市:" + arr[1] + "\n区:" + arr[2]);

        String s = arr[1];
        s = s.substring(0, s.length() - 1);

        List<MallDealerVo> dealerList = mallDealerMapper.selectByArea(s);

        if (dealerList.size() == 0) {
            return ServerResponse.createByErrorCodeMessage(90, "无匹配的办事处");
        }

        MallDealerVo mallDealerVo = dealerList.get(0);
        mallDealerVo.setProvince(arr[0]);
        mallDealerVo.setCity(arr[1]);
        mallDealerVo.setCountry(arr[2]);

        List<MallDealerVo> result = new ArrayList<>();
        result.add(mallDealerVo);

        return ServerResponse.createBySuccess(result);
    }

    @GetMapping("GetMyDealer")
    @ApiOperation(value = "获取指定用户的经销商")
    public ServerResponse GetMyDealer(String token) throws Exception {
        Jedis jedis = jedisPool.getResource();

        SysUser user = tokenUtil.tokenToUser(jedis, token).getData();
        System.out.println("user=" + user);

        SysUser sysUser = sysUserMapper.selectByPrimaryKey(user.getUserId());

        if (sysUser == null) {
            return ServerResponse.createByErrorCodeMessage(12, "用户不存在或token失效");
        }

        if (sysUser.getDealer_id() == null) {
            return ServerResponse.createByErrorCodeMessage(90, "用户未绑定办事处");
        }

        MallDealer mallDealer = mallDealerMapper.selectByPrimaryKey(sysUser.getDealer_id());

        return ServerResponse.createBySuccess(mallDealer);
    }
}
